#coding:utf-8
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading
import urlparse
import random
import re
import os
userdict={}
class GetHandler(BaseHTTPRequestHandler):
    def doit(self):   #重写这个方法
        parsed_path = urlparse.urlparse(self.path)
        spath=parsed_path.path.strip('/')
        setcookie=''
        if 'Cookie' in self.headers:
            print 'saved user:',userdict[self.headers['Cookie']]
        if 'Content-Length' in self.headers and spath!="file/upload":
            postlength = int(self.headers['Content-Length'])
            postdata=self.rfile.read(postlength)
            print 'POST',postdata
        if spath=="question/list":
            message='{"uname":"呵呵呵","question":[{"title":"你知道吗","state":1,"utime":1387677523,"desc":"一个测试","qid":1},{"title":"不知道呀","state":2,"utime":1384677523,"desc":"第二个测试","qid":2},{"title":"呀~~~","state":0,"utime":1387657523,"desc":"第三个测试","qid":3},{"title":"嚯！！！","state":-1,"utime":1377677523,"desc":"第四个测试","qid":4}]}'
        elif spath=="login":
            uname=postdata.split('&')[0].split('=')[1]
            pwd=postdata.split('&')[1].split('=')[1]
            if (uname,pwd) in [('1','784efc504f8ca7ed942773dc669278'),('2','2')]:
                print uname,'login'
                setcookie='sid=%016x' % random.randrange(16**30)
                userdict[setcookie]=uname
            message='{"uname":"呵呵呵","level":2,"uid":11,"msg":"ok"}'
        elif spath=="user/forget_pwd":
            message='{"token":"2333333","msg":"ok"}'
        elif spath=="question/detail":
            message='{"qid":"1","title":"111","desc":"222","status":1,"answer":"333"}'
        elif spath=="file/list":
            message='{"files":[{"filename":"233.avi","size":1515214523,"utime":1387677523,"hash":"6584ac1892b269cf5e5fa2b3c3b8ea6a"},{"filename":"IODS-123.mkv","size":712387123,"utime":1385526325,"hash":"16a98191134e46a2c754dd1f406991c4"},{"filename":"【SIS01】圣诞节打包.torrent","size":51223,"utime":1386885241,"hash":"fe1889655c9651b9cf32e45d0536b752"},{"filename":"线性代数-第一讲.avi","size":598271632,"utime":1369874525,"hash":"ae0fcc4f623ac2f480424d1cb67a86cb"}]}'
        elif spath=="file/upload":
            self.deal_post_data()
            message="{'msg':'ok'}"
        elif spath.startswith("file/download"):
            message=open(r'z:/MAClient1.64_131223.rar','rb').read()
            print len(message)
        elif spath=="im/talk":
            message="{'msg':'ok'}"
        else:
            message="{'msg':'ok','query':'"+spath+"'}"
        
        self.send_response(200)  #返回给客户端结果，这里的响应码是200 OK，并包含一些其他信息
        if setcookie:
            self.send_header('Set-Cookie',setcookie)
        if spath.startswith("file/download"):
            self.send_header('Content-length',len(message))
        self.end_headers() #结束头信息
        self.wfile.write(message) #返回数据
        return

    def deal_post_data(self):
        boundary = self.headers.plisttext.split("=")[1]
        remainbytes = int(self.headers['content-length'])
        remainbytes -= len(self.rfile.readline())
        line = self.rfile.readline()
        remainbytes -= len(line)
        fn = re.findall(r'Content-Disposition.*name="file"; filename="(.*)"', line)[0]
        fn=os.path.join('z:/',fn)
        out=open(fn,'wb')
        remainbytes -= len(self.rfile.readline())
        line = self.rfile.readline()
        remainbytes -= len(line)
        preline = self.rfile.readline()
        remainbytes -= len(preline)
        while remainbytes > 0:
            line = self.rfile.readline()
            remainbytes -= len(line)
            if boundary in line:
                preline = preline[0:-1]
                if preline.endswith('\r'):
                    preline = preline[0:-1]
                out.write(preline)
                out.close()
                print ("File '%s' upload success!" % fn)
                return
            else:
                out.write(preline)
                preline = line
        print ("Unexpect Ends of data.")

    do_HEAD=do_POST=do_GET=doit
class ThreadedHTTPServer(HTTPServer):
    pass
if __name__ == '__main__':
    from BaseHTTPServer import HTTPServer
    server =  ThreadedHTTPServer(('localhost', 8080), GetHandler) #在本地8080端口上启用httpserver，使用自定义的GetHandler处理
    print 'Starting server, use <Ctrl-C> to stop'
    server.serve_forever()  #保存程序一直运行